﻿using Log.Recorder.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace Log.Recorder
{
    /// <summary>
    /// 日志读录器
    /// </summary>
    public class LogReader
    {
        private LogRecorder logger = new LogRecorder();

        /// <summary>
        /// 获取日志数据库列表
        /// </summary>
        /// <param name="yearStr"></param>
        /// <param name="monthStr"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public List<LogDbFileInfo> GetLogDbFileList(string yearStr = "", string monthStr = "", string level = "")
        {

            List<LogDbFileInfo> res = new List<LogDbFileInfo>();
            string logPath = LogConfig.LogDbPathRoot;

            if (!Directory.Exists(logPath))
            {
                return res;
            }

            DirectoryInfo root = new DirectoryInfo(logPath);
            foreach (DirectoryInfo year in root.GetDirectories())
            {
                if (!string.IsNullOrEmpty(yearStr) && yearStr != year.Name) { continue; }
                foreach (DirectoryInfo month in year.GetDirectories())
                {
                    if (!string.IsNullOrEmpty(monthStr) && monthStr != month.Name) { continue; }

                    foreach (FileInfo logFile in month.GetFiles())
                    {

                        if (
                            logFile.Name.Contains("-journal") ||
                            (!string.IsNullOrEmpty(level) && !logFile.Name.Contains(level))
                         )
                        {
                            continue;
                        }

                        try
                        {
                            LogDbFileInfo logDb = new LogDbFileInfo();
                            logDb.year = year.Name;
                            logDb.month = month.Name;
                            logDb.fileName = logFile.Name;
                            logDb.filePath = string.Format(@"{0}\{1}\{2}", year.Name, month.Name, logFile.Name);
                            logDb.fileUpdateTime = logFile.LastWriteTime;
                            logDb.fileSize = logFile.Length;

                            logDb.date = logFile.Name.Substring(0, 8);
                            logDb.level = Path.GetFileNameWithoutExtension(logFile.Name).Replace(logDb.date + "_", "");
                            logDb.logTime = DateTime.Parse(logDb.year + "-" + logDb.month + "-" + logFile.Name.Substring(6, 2) + " 00:00:00");

                            res.Add(logDb);
                        }
                        catch (Exception exp)
                        {
                            logger.Error("读取日志列表异常。文件“" + logFile.Name + "”不符合日志数据命名格式。" + exp.Message, exp);
                        }
                    }
                }
            }

            return res;

        }

        /// <summary>
        /// 获取日志列表
        /// </summary>
        /// <param name="DbFilePath">数据库相对URL</param>
        /// <param name="bTime">开始时间</param>
        /// <param name="eTime">结束时间</param>
        /// <param name="Type">类型</param>
        /// <param name="Message">消息</param>
        /// <param name="Data">数据</param>
        /// <returns></returns>
        public List<Dictionary<string, object>> GetLogs(string DbFilePath
                , string bTime = "", string eTime = "", string Type = "", string Message = "", string StackTrace = "", string Data = ""
            )
        {

            using (DbWriter dbWriter = new DbWriter(DbWriterPool.GetConnectionStringByLogType(DbFilePath))) {
                using (DataTable dt = dbWriter.GetLogs(bTime, eTime, Type, Message, StackTrace, Data))
                {
                    List<Dictionary<string, object>> table = new List<Dictionary<string, object>>();

                    foreach (DataRow row in dt.Rows)
                    {
                        Dictionary<string, object> _row = new Dictionary<string, object>();
                        _row["fileName"] = Path.GetFileName(DbFilePath);
                        _row["filePath"] = DbFilePath;
                        foreach (DataColumn dc in dt.Columns)
                        {
                            _row[dc.ColumnName] = row[dc.ColumnName];
                        }
                        table.Add(_row);
                    }

                    return table;
                }

            }
        }

        /// <summary>
        /// 分页获取日志列表
        /// </summary>
        /// <param name="pageSize">页大小</param>
        /// <param name="pageNumber">页面</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="sortType">排序类型。值：asc desc </param>
        /// <param name="dbFilePath">数据库相对URL</param>
        /// <param name="bTime">开始时间</param>
        /// <param name="eTime">结束时间</param>
        /// <param name="type">类型</param>
        /// <param name="message">消息</param>
        /// <param name="stackTrace">日志记录位置</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public PagingLogData<Dictionary<string, object>> GetLogsByPage(int pageSize, int pageNumber, string sortField, string sortType
            ,string dbFilePath, string bTime, string eTime, string type, string message, string stackTrace, string data)
        {

            using (DbWriter dbWriter = new DbWriter(DbWriterPool.GetConnectionStringByLogType(dbFilePath)))
            {
                PagingLogData pData = dbWriter.GetLogsByPage(pageSize, pageNumber, sortField, sortType, bTime, eTime, type, message, stackTrace, data);
                PagingLogData<Dictionary<string, object>> resPage = new PagingLogData<Dictionary<string, object>>();
                resPage.pagenumber = pData.pagenumber;
                resPage.pagesize = pData.pagesize;
                resPage.total = pData.total;
                resPage.rows = new List<Dictionary<string, object>>();
                foreach (DataRow row in pData.rows.Rows)
                {
                    Dictionary<string, object> _row = new Dictionary<string, object>();
                    _row["fileName"] = Path.GetFileName(dbFilePath);
                    _row["filePath"] = dbFilePath;
                    foreach (DataColumn dc in pData.rows.Columns)
                    {
                        _row[dc.ColumnName] = row[dc.ColumnName];
                    }
                    resPage.rows.Add(_row);
                }

                return resPage;
            }
        }

        /// <summary>
        /// 获取日志数据
        /// </summary>
        /// <param name="DbFilePath">数据库相对URL</param>
        /// <param name="ID">日志ID</param>
        /// <returns></returns>
        public object GetLogData(string DbFilePath, string ID)
        {
            DbWriter dbWriter = null;
            try
            {
                dbWriter = new DbWriter(DbWriterPool.GetConnectionStringByLogType(DbFilePath));
                return dbWriter.GetLogData(ID);
            }
            catch (Exception exp) { throw exp; }
            finally
            {
                if (dbWriter != null)
                {
                    dbWriter.Dispose();
                }
            }
        }
        /// <summary>
        /// 获取日志数据
        /// </summary>
        /// <param name="DbFilePath">数据库相对URL</param>
        /// <param name="ID">日志ID</param>
        /// <returns></returns>
        public DataTable GetLogData2(string DbFilePath, string ID)
        {
            DbWriter dbWriter = null;
            try
            {
                dbWriter = new DbWriter(DbWriterPool.GetConnectionStringByLogType(DbFilePath));
                return dbWriter.GetLogData2(ID);
            }
            catch (Exception exp) { throw exp; }
            finally
            {
                if (dbWriter != null)
                {
                    dbWriter.Dispose();
                }
            }
        }

    }
}
